use axum::{Router, Extension};
use dotenvy::dotenv;
use sqlx::mysql::MySqlPoolOptions;
use std::env;
use std::net::SocketAddr;
use tower_http::cors::CorsLayer;
use tower_http::trace::TraceLayer;
use tracing_subscriber;

mod routes;
mod models;
mod handlers;
mod services;
mod repositories;
mod errors;
mod utils;

#[tokio::main]
async fn main() { 

    // 初始化日志
    tracing_subscriber::fmt::init();

    // 加载环境变量
    dotenv().ok();

    // 创建数据库连接池
    let db_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set");
    let db_pool = MySqlPoolOptions::new()
        .max_connections(5)
        .connect(&db_url)
        .await
        .expect("Failed to create database pool.");

    // 创建路由
    let app = Router::new()
        .merge(routes::user_routes())
        .merge(routes::auth_routes())
        .layer(Extension(db_pool))
        .layer(CorsLayer::permissive())
        .layer(TraceLayer::new_for_http());

    // 启动服务器
    let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
    tracing::info!("Listening on {}", addr);
    
    let listener = tokio::net::TcpListener::bind(addr).await.unwrap();
    axum::serve(listener, app).await.unwrap();
}
